package edu.hz.service.impl;

import edu.hz.dao.ClazzMapper;
import edu.hz.dao.GradeMapper;
import edu.hz.dao.UserDonationMapper;
import edu.hz.dao.UserMapper;
import edu.hz.enums.UserTitle;
import edu.hz.model.dto.HomeMostContributePeopleDto;
import edu.hz.model.dto.UserContributeDto;
import edu.hz.model.dto.UserLoginDto;
import edu.hz.model.dto.UserRegisterDto;
import edu.hz.model.entity.UserDonationEntity;
import edu.hz.model.entity.UserEntity;
import edu.hz.service.UserService;
import edu.hz.util.PasswordUtil;
import edu.hz.util.web.ApiResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    GradeMapper gradeMapper;

    @Resource
    ClazzMapper clazzMapper;


    @Value("5")
    private Integer errLoginCount;

    @Resource
    private UserDonationMapper userDonationMapper;

    @Override
    public ApiResponse<Void> addUser(UserRegisterDto userRegisterDto) {

        // 判断用户名是否重复
        if (isUsernameExist(userRegisterDto.getUsername())) {
            return ApiResponse.error("用户名已经被占用了");
        }


        // 填写的两次密码是否一致
        if (!userRegisterDto.getPassword().equals(userRegisterDto.getPasswordConfirm())) {
            return ApiResponse.error("两次输入的密码不一致");
        }

        // 判断年级是否存在
        if (gradeMapper.getGradeById(userRegisterDto.getGradeId()) == null) {
            return ApiResponse.error("选择的年级不存在");
        }

        // 判断班级是否存在
        if (clazzMapper.getClazzById(userRegisterDto.getClazzId()) == null) {
            return ApiResponse.error("选择的班级不存在");
        }

        // 判断性别是否正确
        if (userRegisterDto.getGender() < 0 || userRegisterDto.getGender() > 2) {
            return ApiResponse.error("性别不正确");
        }

        // 构建 ENTITY
        UserEntity user = new UserEntity();
        user.setUsername(userRegisterDto.getUsername());
        user.setSchoolId(userRegisterDto.getSchoolId());
        user.setRealname(userRegisterDto.getRealname());
        user.setGender(userRegisterDto.getGender());
        user.setGradeId(userRegisterDto.getGradeId());
        user.setClazzId(userRegisterDto.getClazzId());

        // 生成密文密码
        String salt = PasswordUtil.generateSalt();
        String encryptedPassword = PasswordUtil.hashPassword(userRegisterDto.getPassword(), salt);
        user.setPwd(encryptedPassword);
        user.setPwdSalt(salt);

        // 设置初始称号
        user.setTitle(UserTitle.HEARTHED_PERSON.getTitle());
        user.setMoney(0);

        // 插入数据库
        userMapper.insertUser(user);

        return ApiResponse.success(null);
    }

    @Override
    public ApiResponse<String> login(UserLoginDto userLoginDto) {
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();

        UserEntity userEntity = userMapper.getUserByUsername(username);
        if (userEntity == null) {
            return ApiResponse.error("用户没有，登录失败");
        }

        Integer currentErrorLoginCount = userEntity.getErrLoginCount();

        if (currentErrorLoginCount > errLoginCount) {
            return ApiResponse.error("帐号被冻结");
        }

        String pwd = userEntity.getPwd();

        String encryptedPwd = PasswordUtil.hashPassword(password, userEntity.getPwdSalt());

        if (!encryptedPwd.equals(pwd)) {
            Integer errLoginCount = userEntity.getErrLoginCount();
            Integer afterErrorLogin = errLoginCount + 1;
            userMapper.updateErrLoginCount(userEntity.getId(), afterErrorLogin);
            return ApiResponse.error("登录失败");
        }

        userMapper.updateErrLoginCount(userEntity.getId(), 0);

        return ApiResponse.success("登录成功");
    }

    @Override
    public ApiResponse<Void> userContribute(UserContributeDto userContributeDto) {


        UserDonationEntity entity = new UserDonationEntity();
        entity.setUserId(userContributeDto.getUserId());
        entity.setDonationId(userContributeDto.getDonationId());
        entity.setDonationType(userContributeDto.getDonationType().getValue());
        entity.setMoney(userContributeDto.getMoney());
        entity.setDetail(userContributeDto.getDetail());

        entity.setDonationTime(LocalDateTime.now());

        int result = userDonationMapper.insertUserDonation(entity);

        return result > 0 ? ApiResponse.success(null) : ApiResponse.error("捐献失败，重试");
    }

    @Override
    public ApiResponse<List<HomeMostContributePeopleDto>> top10Contributors() {
        List<HomeMostContributePeopleDto> retList = userMapper.mostContributePeople(10);
        return ApiResponse.success(retList);
    }


    private boolean isUsernameExist(String username) {
        return userMapper.getUserByUsername(username) != null;
    }

}
